from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import ttk, messagebox
from pydocx import PyDocX
from bs4 import BeautifulSoup
import os

# 默认style
init_style = """
* { margin: 0;padding: 0;}
body { padding: 10px !important;}
table td {border-style: solid;}
"""


class DocToHtml:
    def __init__(self, file):
        self.soup = None
        self.file = file
    # 获取文档内容

    def get_doc_content(self):
        html = PyDocX.to_html(self.file)
        self.soup = BeautifulSoup(html, 'lxml')  # 使用lxml解析库

    # 修改html内容
    def update_html(self):
        # 插入新的meta
        meta = self.soup.new_tag(
            'meta', content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;')
        self.soup.head.insert(1, meta)
        # 删除style
        self.soup.style.clear()
        self.soup.style.append(init_style)
        # 格式化代码，自动补全代码
        self.soup.prettify()

    # 生成html文件
    def save_html(self):
        filename = os.path.basename(self.file)
        path = os.path.dirname(self.file)
        print(os.path.dirname(self.file))
        f = open(path + '/' + filename+'.html', 'w', encoding="utf-8")
        f.write(str(self.soup))
        f.close()
        messagebox.showinfo(title='信息提示！', message='转换完成')

    def run(self):
        self.get_doc_content()
        self.update_html()
        self.save_html()


class Application():
    def __init__(self, tk):
        self.tk = tk
        self.filePath = ''
        self.fileName = StringVar()
        self.fileType = 'html'

    # 设置窗口
    def init_window(self):

        # 文件选择
        row1 = Frame(self.tk, relief=RAISED, pady=10)
        row1 .pack(side=TOP, fill=BOTH, ipadx=13, expand=0)

        file_label = Label(row1, text="选择文档：", font=('微软雅黑', 10))
        file_label.pack(side=LEFT, anchor='nw')

        upload_button = Button(row1, {
            'text': '选择文件',
            'bg': "#00a4ff",
            'bd': 0,
            'fg': "#ffffff",
            'command': self.open_file
        })
        upload_button.pack(side=LEFT, anchor='nw')

        fileName_text = Label(row1, textvariable=self.fileName)
        fileName_text.pack(side=LEFT, anchor='nw')

        separator = Frame(height=2, bd=1, relief="sunken")
        separator.pack(fill="x", padx=5)

        row2 = Frame(self.tk, relief=RAISED, pady=10)
        row2 .pack(side=TOP, fill=BOTH, ipadx=13, expand=0)

        # # 转换类型
        trans_type = Label(row2, text="转换类型：", font=('微软雅黑', 10))
        trans_type.pack(side=LEFT, anchor='nw')

        select_ment = ttk.Combobox(row2, state="readonly", font=(
            "微软雅黑", 10), value=("html", 'pdf'))
        select_ment.bind("<<ComboboxSelected>>", self.select_cb)
        select_ment.current(0)
        select_ment.pack(side=LEFT, anchor='nw')

        separator = Frame(height=2, bd=1, relief="sunken")
        separator.pack(fill="x", padx=5)

        # # 按钮
        row3 = Frame(self.tk, relief=RAISED, pady=10)
        row3 .pack()
        button = Button(row3, {
            'width': '15',
            'text': '确 定',
            'bg': "#00a4ff",
            'bd': 0,
            'fg': "#ffffff",
            'anchor': 'center'
        })
        button.config(command=self.submit_click)
        button.pack()

    # 窗口居中
    def center_window(self, width, height):
        winWdith = self.tk.winfo_screenwidth()
        winHeight = self.tk.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height,
                                (winWdith-width)/2, (winHeight-height)/2)
        return size

    # 打开文件选择框
    def open_file(self):
        filetypes = (("文档文件", ("*.doc", "*.docx")), ('所有文件', "*.*"))
        file = askopenfilename(filetypes=filetypes)
        filename = os.path.basename(file)
        self.filePath = file
        self.fileName.set(filename)
       
        print(filename)

    def select_cb(self, value):
        print(value.widget.get())
        return value

    def submit_click(self):
        if self.filePath.endswith(".doc") or self.filePath.endswith(".docx"):
            DocToHtml(self.filePath).run()
        else:
            messagebox.showerror(title='信息提示！', message='上传文件格式错误')


def run_gui():
    tk = Tk()
    # 设置窗口标题
    tk.title("文档转换工具")
    # 实例化出一个父窗口
    app = Application(tk)
    # 设置窗口大小位置
    size = app.center_window(400, 300)
    tk.geometry(size)
    # 设置根窗口默认属性
    app.init_window()

    # 父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示
    tk.mainloop()


run_gui()
